using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using UnityEngine;
using UnityEngine.InputSystem;
using static EntityManager;

partial struct RaycastSystem : ISystem
{
    public static int id;
    private static bool click;
    private Entity hitEntity;
    private NativeList<Unity.Physics.RaycastHit> _hits;

    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        _hits = new NativeList<Unity.Physics.RaycastHit>(Allocator.Persistent);
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        var camera = GameObject.FindObjectOfType<Camera>();
        if (camera == null)
            return;
        
        if (click)
        {
            click = false;
            var physicsWorld = SystemAPI.GetSingleton<PhysicsWorldSingleton>();
            var pos = camera.ScreenPointToRay(Mouse.current.position.ReadValue());
            var rayInput = new RaycastInput
            {
                Start = pos.origin,
                End = pos.origin + pos.direction * 1000,
                Filter = CollisionFilter.Default
            };
            if (physicsWorld.CastRay(rayInput, out var hit))
            {
                var entity = physicsWorld.Bodies[hit.RigidBodyIndex].Entity;
                if (hitEntity != entity)
                {
                    if (hitEntity != Entity.Null)
                        SelectEntity(hitEntity, false);
                    hitEntity = physicsWorld.Bodies[hit.RigidBodyIndex].Entity;
                }
                SelectEntity(hitEntity, true);
                if (id != 0)
                {
                    var p = GetEntityPos(hitEntity);
                    var findEntity = GetEntityByPos(p);
                    if (findEntity != Entity.Null)
                    {
                        Manager.AddComponentData(findEntity, new DestroyComponent());
                    }
                    ResourceManager.LoadObjectToEntity(id, p);
                }
            }
        }
    }

    [BurstCompile]
    public void OnDestroy(ref SystemState state)
    {
        _hits.Dispose();
    }

    private readonly void SelectEntity(Entity entity, bool select)
    {
        if (select)
        {
            //SetEntityScale(entity, 1.1f);
            SetEntityMaterial(entity, 2);
        }
        else
        {
            //SetEntityScale(entity, 1);
            SetEntityMaterial(entity, -1);
        }
    }

    public static void OnClick() => click = true;

    public readonly float3 GetSelectPos() => GetEntityPos(hitEntity);
}
